import { Component, ReactNode, PureComponent } from 'react';
import { createPortal } from 'react-dom'
// 引入样式
import "./index.css"

// 封装的目的，提示组件的复用性

type Iprops = {
    title?:string // 标题
    children?:ReactNode // 主体内容
    onOk?:()=> void // 点击确定按钮的回调
    onCancel?:()=> void // 点击取消按钮的回调
    open?:boolean // 控制显示和隐藏
}
// 声明state类型
type Istate = {
    visible:boolean // 组件内部状态，控制组件显示和隐藏
    isClose:boolean // 标记是否点击了关闭按钮
}
// 声明类的属性
type m = {
    dv:HTMLElement
}
class Modal extends PureComponent<Iprops,Istate> implements m {
    state = {
        visible:false,
        isClose:true,
    }
    dv = document.createElement("div")

    // 一个全新的钩子函数
    static getDerivedStateFromProps(nextProps:Iprops,nextState:Istate):Object | null {
        // console.log(nextProps);
        console.log(nextState);
        let {isClose,visible} = nextState // 从nextState中解构出来
        if (isClose) {
            // 点击了关闭按钮
            return {
                visible,
                isClose:false // 重置开关
            }
        }else{
            return {
                visible:nextProps.open
            }
        }
        
    }

    componentDidMount(): void {
        this.dv.id = 'modal-root';
        document.body.appendChild(this.dv)
    }
    componentWillUnmount(): void {
        // 先判断是否存在modalRoot，有就把modalRoot移除掉
        let modalRoot = document.getElementById('modal-root')
        modalRoot && document.body.removeChild(modalRoot)
    }

    // 点击X关闭
    handleClose = () => {
        this.setState({
            visible:false,
            isClose:true
        })
    }

    render(): ReactNode {
        let { visible } = this.state
        let {children,title,onCancel,onOk} = this.props // 从props解构出来
        let el = (
            <div className="modal-container">
                <div className="modal-mask">
                    <div className="modal-content">
                        <button onClick={this.handleClose} className="close">×</button>
                        <div className="header">
                            {title ?? '提示'}
                        </div>
                        <div className="body">
                            {children?children:'内容'}
                        </div>
                        <div className="footer">
                            <button onClick={()=>{
                                onCancel && onCancel()
                            }} className="cancel">取消</button>
                            <button onClick={()=>{
                                onOk && onOk()
                            }} className="confirm">确定</button>
                        </div>
                    </div>
                </div>
            </div>
        )
        return visible ? createPortal(el,this.dv) : null
    }
}
export default Modal